// index.js
Page({
  data: {
    isLoading: true,
    hasUserInfo: false,
    currentTab: 0,
    
    // --- 学习模块 ---
    learningMode: 'python', // python, numpy
    pythonData: [],
    numpyData: [],
    studyCategories: [],
    selectedCategory: 0,
    currentArticle: null, // 控制学习模块详情页显示
    currentNumpyArticle: null, // 控制numpy模块详情页显示
    numpyCodeInput: '', // numpy代码输入
    showNumpyLab: false, // 是否显示实验代码测试区

    // --- 编程模块 ---
    programmingMode: 'practice', // practice, algorithm
    algorithmCategories: [],
    practiceCategories: [],
    practiceProblems: [],
    selectedProgrammingCategory: 0,
    currentAlgorithmArticle: null, // 控制算法模块详情页
    currentProblem: null, // 控制刷题模块详情页
    
    // 缓存数据
    algorithmData: [], 
    
    // 代码提交
    codeInput: '',
    showLoginModal: true,
  },

  onLoad() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ showLoginModal: false, hasUserInfo: true });
      this.loadInitialData && this.loadInitialData();
    } else {
      this.setData({ showLoginModal: true, hasUserInfo: false });
    }
  },

  loadInitialData() {
    // 默认仅加载学习模块的分类和数据
    this.loadStudyCategories();
  },

  // 切换底部总标签 
  switchTab(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    if (this.data.currentTab === index) return;
    this.setData({ currentTab: index });
    if (index === 1 && this.data.practiceCategories.length === 0) {
      this.loadPracticeCategories();
    }
  },

  // --- 学习模块逻辑 ---
  switchLearningMode(e) {
    const mode = e.currentTarget.dataset.mode;
    if (this.data.learningMode !== mode) {
      this.setData({
        learningMode: mode,
        currentArticle: null, // 切换时重置详情页
        currentNumpyArticle: null, // 重置numpy详情页
        numpyCodeInput: '', // 重置numpy代码输入
        showNumpyLab: false, // 重置实验区
      }, () => {
        this.loadStudyCategories();
      });
    }
  },

  loadStudyCategories() {
    const that = this;
    const mode = this.data.learningMode;
    const endpoints = {
      python: 'http://192.168.1.74:8081/learn/list',
      numpy: 'http://192.168.1.74:8081/learn/numpy/list',
    };
    const url = endpoints[mode];

    wx.showLoading({
      title: '加载中...',
      mask: true,
    });

    wx.request({
      url: url,
      method: 'GET',
      success(res) {
        if (res.statusCode === 200) {
          let processedData = that.processGroupedData(res.data.data);
          // Numpy模式下添加"实验代码测试"虚拟项
          if (mode === 'numpy') {
            processedData.push({
              id: 'numpy-lab',
              title: '实验代码测试',
              items: []
            });
          }
          that.setData({
            studyCategories: processedData,
            selectedCategory: 0,
            currentArticle: null,
          });
        } else {
          console.error(`获取${mode}数据失败:`, res.data.msg || '无错误信息');
          wx.showToast({
            title: '数据加载失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      },
      complete() {
        wx.hideLoading();
      }
    });
  },

  selectCategory(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const selected = this.data.studyCategories[index];
    if (this.data.learningMode === 'numpy' && selected && selected.id === 'numpy-lab') {
      this.setData({
        selectedCategory: index,
        currentArticle: null,
        currentNumpyArticle: null,
        numpyCodeInput: '',
        showNumpyLab: true
      });
    } else {
      this.setData({ 
        selectedCategory: index,
        currentArticle: null, // 返回列表
        currentNumpyArticle: null, // 重置numpy详情页
        numpyCodeInput: '', // 重置numpy代码输入
        showNumpyLab: false
      });
    }
  },

  selectArticle(e) {
    const article = e.currentTarget.dataset.article;
    if (this.data.learningMode === 'numpy') {
      this.setData({ currentNumpyArticle: article, numpyCodeInput: '' });
    } else {
      this.setData({ currentArticle: article });
    }
  },

  backToList() {
    if (this.data.learningMode === 'numpy') {
      this.setData({ currentNumpyArticle: null, numpyCodeInput: '', showNumpyLab: false });
    } else {
      this.setData({ currentArticle: null });
    }
  },


  // --- 编程模块逻辑 ---
  switchProgrammingMode(e) {
    const mode = e.currentTarget.dataset.mode;
    if (mode === this.data.programmingMode) return;
    this.setData({ 
      programmingMode: mode, 
      selectedProgrammingCategory: 0,
      currentAlgorithmArticle: null,
      currentProblem: null
    });
    
    if (mode === 'algorithm' && this.data.algorithmCategories.length === 0) {
      this.loadAlgorithmCategories();
    } else if (mode === 'practice' && this.data.practiceCategories.length === 0) {
      this.loadPracticeCategories();
    }
  },

  loadAlgorithmCategories() {
    const that = this;
    wx.showLoading({ title: '加载中...' });
    wx.request({
      url: 'http://192.168.1.74:8081/learn/algorithm/list',
      method: 'GET',
      success(res) {
        if (res.statusCode === 200) {
          const processedData = that.processGroupedData(res.data.data);
          that.setData({
            algorithmCategories: processedData,
            selectedProgrammingCategory: 0
          });
        } else {
          wx.showToast({ title: '算法数据加载失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络请求失败', icon: 'none' }),
      complete: () => wx.hideLoading()
    });
  },

  loadPracticeCategories() {
    const that = this;
    wx.showLoading({ title: '加载中...' });
    wx.request({
      url: 'http://192.168.1.74:8081/learn/algorithm/list',
      method: 'GET',
      success(res) {
        if (res.statusCode === 200 && res.data.code === 0) {
          const processedData = that.processGroupedData(res.data.data);
          that.setData({ practiceCategories: processedData });
          if (processedData && processedData.length > 0) {
            that.loadPracticeProblems(processedData[0].id);
          }
        } else {
          wx.showToast({ title: '章节数据加载失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络请求失败', icon: 'none' }),
      complete: () => wx.hideLoading()
    });
  },

  loadPracticeProblems(chapterId) {
    const that = this;
    wx.showLoading({ title: '加载题目...' });
    wx.request({
      url: `http://192.168.1.74:8081/algorithm/chapter/${chapterId}`,
      method: 'GET',
      success(res) {
        if (res.statusCode === 200) {
          that.setData({ practiceProblems: res.data.data || [] });
        } else {
          wx.showToast({ title: '题目加载失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络请求失败', icon: 'none' }),
      complete: () => wx.hideLoading()
    });
  },
  
  selectProgrammingCategory(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({ 
      selectedProgrammingCategory: index,
      currentAlgorithmArticle: null,
      currentProblem: null
    });
    if (this.data.programmingMode === 'practice') {
      const chapterId = this.data.practiceCategories[index].id;
      this.loadPracticeProblems(chapterId);
    }
  },

  selectAlgorithmArticle(e) {
    this.setData({ currentAlgorithmArticle: e.currentTarget.dataset.article });
  },

  backToAlgorithmList() {
    this.setData({ currentAlgorithmArticle: null });
  },

  selectPracticeProblem(e) {
    this.setData({ currentProblem: e.currentTarget.dataset.problem, codeInput: '' });
  },

  backToProblemList() {
    this.setData({ currentProblem: null, codeInput: '' });
  },

  // --- 通用和辅助函数 ---
  processGroupedData(data) {
    const chapters = {};
    if (!Array.isArray(data)) {
      console.error("Data is not an array for grouping:", data);
      return [];
    }
    data.forEach(item => {
      const chapterId = item.knowledgeChapterId;
      if (!chapters[chapterId]) {
        chapters[chapterId] = {
          id: chapterId,
          title: item.chapterName,
          items: []
        };
      }
      chapters[chapterId].items.push({
        id: item.knowledgeId,
        title: item.knowledgeTitle,
        text: item.text,
      });
    });
    return Object.values(chapters);
  },

  // --- 代码提交逻辑 ---
  onCodeInput(e) {
    this.setData({
      codeInput: e.detail.value
    });
  },

  onNumpyCodeInput(e) {
    this.setData({
      numpyCodeInput: e.detail.value
    });
  },

  submitNumpyCode() {
    if (!this.data.numpyCodeInput.trim()) {
      return wx.showToast({ title: '请输入代码', icon: 'none' });
    }
    // 微信小程序兼容的 base64 编码
    function encodeBase64(str) {
      return wx.arrayBufferToBase64(new TextEncoder().encode(str));
    }
    const submitData = {
      problemId: this.data.currentNumpyArticle.id,
      code: encodeBase64(this.data.numpyCodeInput)
    };
    wx.showLoading({ title: '提交中...' });
    wx.request({
      url: 'http://192.168.1.74:8081/submit/check',
      method: 'POST',
      data: submitData,
      success: (res) => {
        if (res.data && res.data.code === 200) {
          wx.showToast({ title: res.data.msg || '提交成功', icon: 'success' });
        } else {
          wx.showToast({ title: (res.data && res.data.msg) || '提交失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络错误，请重试', icon: 'none' }),
      complete: () => wx.hideLoading()
    });
  },

  submitCode() {
    if (!this.data.codeInput.trim()) {
      return wx.showToast({ title: '请输入代码', icon: 'none' });
    }
    // 微信小程序兼容的 base64 编码
    function encodeBase64(str) {
      return wx.arrayBufferToBase64(new TextEncoder().encode(str));
    }
    const submitData = {
      problemId: this.data.currentProblem.id,
      code: encodeBase64(this.data.codeInput)
    };
    wx.showLoading({ title: '提交中...' });
    wx.request({
      url: 'http://192.168.1.74:8081/submit/check',
      method: 'POST',
      data: submitData,
      success: (res) => {
        if (res.data && res.data.code === 200) {
          wx.showToast({ title: res.data.msg || '提交成功', icon: 'success' });
        } else {
          wx.showToast({ title: (res.data && res.data.msg) || '提交失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络错误，请重试', icon: 'none' }),
      complete: () => wx.hideLoading()
    });
  },

  onLoginTap() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (userRes) => {
        wx.login({
          success: (res) => {
            if (res.code) {
              wx.request({
                url: 'http://192.168.1.74:8081/user/login',
                method: 'POST',
                data: {
                  code: res.code,
                  userInfo: userRes.userInfo
                },
                success: (serverRes) => {
                  wx.setStorageSync('userInfo', userRes.userInfo);
                  this.setData({
                    hasUserInfo: true,
                    showLoginModal: false // 登录成功后关闭弹窗
                  });
                  wx.showToast({ title: '登录成功', icon: 'success' });
                  this.loadInitialData(); // 登录成功后加载主页面数据
                },
                fail: () => {
                  wx.showToast({ title: '登录失败', icon: 'none' });
                }
              });
            }
          }
        });
      },
      fail: (err) => {
        console.log(err)
        wx.showToast({ title: '授权失败', icon: 'none' });
      }
    });
  },

  onGetUserInfo(e) {
    if (e.detail.userInfo) {
      wx.login({
        success: (res) => {
          if (res.code) {
            wx.request({
              url: 'http://192.168.1.74:8081/user/login',
              method: 'POST',
              data: {
                code: res.code,
                userInfo: e.detail.userInfo
              },
              success: (serverRes) => {
                wx.setStorageSync('userInfo', e.detail.userInfo);
                this.setData({
                  hasUserInfo: true,
                  showLoginModal: false
                });
                wx.showToast({ title: '登录成功', icon: 'success' });
                this.loadInitialData();
              },
              fail: () => {
                wx.showToast({ title: '登录失败', icon: 'none' });
              }
            });
          }
        }
      });
    } else {
      wx.showToast({ title: '授权失败', icon: 'none' });
    }
  },
});
